package com.itheima.common;

import com.itheima.pojo.Employee;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLIntegrityConstraintViolationException;
import java.time.LocalDateTime;

/**
 * 全局异常处理器
 */
@Slf4j
@ResponseBody
@ControllerAdvice(annotations = {RestController.class, Controller.class})
public class GlobalExceptionHandler {
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex) {
        //打印异常信息
        log.error(ex.getMessage());
        //判断异常信息是否包含指定异常信息
        if (ex.getMessage().contains("Duplicate entry")) {
//        异常信息有空格,所以我们可以通过空格来截取信息,得到一个数组
            String[] split = ex.getMessage().split(" ");
            //索引2位置 获取重复信息
            String msg = split[2] + "已存在";
            //返回异常处理信息
            return R.error(msg);
        }
        return R.error("未知错误");
    }
    /**
     * 异常处理方法
     * @return
     */
    @ExceptionHandler(CustomException.class)//捕获此类型的异常
    public R<String> exceptionHandler(CustomException ex){
        log.error(ex.getMessage());
        return R.error(ex.getMessage());

    }


}
